//
// Created by tcj on 2022/3/3.
//

#include "sylar/sylar.h"
#include "sylar/iomanager.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "fcntl.h"
#include "unistd.h"
#include "arpa/inet.h"

sylar::Logger::ptr  g_logger = SYLAR_LOG_ROOT();

int sock=0;
void test_fiber(){
    SYLAR_LOG_INFO(g_logger)<<"test_fiber";

    sock = socket(AF_INET,SOCK_STREAM,0);
    fcntl(sock,F_SETFL,O_NONBLOCK);

    sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    inet_pton(AF_INET,"192.167.3.171",&addr.sin_addr.s_addr);

    if(!connect(sock,(const sockaddr*)&addr,sizeof(addr))){
    }else if(errno ==EINPROGRESS){
        SYLAR_LOG_INFO(g_logger) <<"add event errno="<<errno<<" "<<strerror(errno);

//        sylar::IOManager::GetThis()->addEvent(sock,sylar::IOManager::READ,[](){
//            SYLAR_LOG_INFO(g_logger)<<"read callback";
//        });
        sylar::IOManager::GetThis()->addEvent(sock,sylar::IOManager::WRITE,[](){
            SYLAR_LOG_INFO(g_logger)<<"write callback";
//            close(sock);
            sylar::IOManager::GetThis()->cancelEvent(sock,sylar::IOManager::READ);
            close(sock);
        });
    }else{
        SYLAR_LOG_INFO(g_logger)<<"else"<<errno<<" "<<strerror(errno);
    }




}

void test1(){

    sylar::IOManager iom(2,true);
    iom.schedule(&test_fiber);


}
sylar::Timer::ptr s_timer;

void test_timer(){
    sylar::IOManager iom(2);
//    iom.addTimer(500,[](){SYLAR_LOG_INFO(g_logger)<<"hello timer";},true);
        s_timer = iom.addTimer(500,[](){
            static int i=0;
            SYLAR_LOG_INFO(g_logger)<<"hello timer"<<i;
            if(++i ==3){
                s_timer->cancel();
            }
        },true);
}


void func_1(){
    SYLAR_LOG_INFO(g_logger)<<"funct_1  testing";
}

void func_2(){
    SYLAR_LOG_INFO(g_logger)<<"funct_2  testing";
}

int main(int argc,char** argv){
//    test1();
//    test_timer();
    sylar::Thread::SetName("test");
    SYLAR_LOG_INFO(g_logger)<<"test begin";
    sylar::IOManager iom;
    iom.schedule(&func_1);
    sylar::Fiber::ptr p(new sylar::Fiber(&func_2));
    iom.schedule(p);
    SYLAR_LOG_INFO(g_logger)<<"test end";
    return 0;

}